import com.mysql.jdbc.jdbc2.optional.MysqlDataSource;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

/**
 * Created with IntelliJ IDEA
 * Description：用这个类来完成数据库建立连接的过程
 * User：chenshu
 * Date：2023-12-04
 * Time：16:48
 */
public class DBUtil {
    private static DataSource dataSource = null;

    //1.使用DataSource描述mysql的服务器位置
    private static DataSource getDataSource() {
        if (dataSource == null) {
            dataSource = new MysqlDataSource();
            ((MysqlDataSource)dataSource).setURL("jdbc:mysql://127.0.0.1:3306/MessageWall?characterEncoding=utf8&useSSL=false");
            ((MysqlDataSource)dataSource).setUser("root");
            ((MysqlDataSource)dataSource).setPassword("sj135433");
        }
        return dataSource;
    }

    //2.建立连接
    public static Connection getConnection() throws SQLException {
        //DataSource的信息有任何错误都会导致连接失败
        return getDataSource().getConnection();
    }

    //5.断开连接
    public static void close(Connection connection, PreparedStatement statement, ResultSet resultSet) {
        if (resultSet!=null) {
            try {
                resultSet.close();
            } catch (SQLException e) {
                throw new RuntimeException(e);
            }
        }
        if (statement != null) {
            try {
                statement.close();
            } catch (SQLException e) {
                throw new RuntimeException(e);
            }
        }
        if (connection != null) {
            try {
                connection.close();
            } catch (SQLException e) {
                throw new RuntimeException(e);
            }
        }
    }
}
